package com.elasticsearch.controller;

import com.elasticsearch.pojo.UserPojo;
import com.elasticsearch.repository.UserRepository;
import com.elasticsearch.util.R;
import io.netty.util.internal.ThreadLocalRandom;
import org.elasticsearch.index.query.MatchQueryBuilder;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.search.sort.SortBuilders;
import org.elasticsearch.search.sort.SortOrder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Sort;
import org.springframework.data.elasticsearch.core.ElasticsearchRestTemplate;
import org.springframework.data.elasticsearch.core.ElasticsearchTemplate;
import org.springframework.data.elasticsearch.core.query.NativeSearchQueryBuilder;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Optional;

/**
 * @author xiaochi
 * @date 2022/3/11 20:45
 * @desc ElasticSearchController
 */
@RestController
@RequestMapping("/es")
public class ElasticSearchController {

    @Autowired
    private ElasticsearchRestTemplate elasticsearchRestTemplate;

    @Autowired
    private UserRepository userRepository;

    /********************************************** UserRepository使用 ********************************************/
    /**
     * 查询所有
     * @return
     */
    @GetMapping("/query")
    public R<Iterable<UserPojo>> query (){
        return R.ok(userRepository.findAll());
    }

    /**
     * 分页排序查询
     * @param pageNum
     * @param pageSize
     * @return
     */
    @GetMapping("/page/{pageNum}/{pageSize}")
    public R<Page<UserPojo>> findPage(@PathVariable Integer pageNum, @PathVariable Integer pageSize){
        NativeSearchQueryBuilder searchQueryBuilder = new NativeSearchQueryBuilder();
        //searchQueryBuilder.withQuery(QueryBuilders.matchQuery("name","小"));
        searchQueryBuilder.withQuery(QueryBuilders.matchAllQuery());
        /*searchQueryBuilder.withPageable(PageRequest.of(pageNum,pageSize));
        searchQueryBuilder.withSort(SortBuilders.fieldSort("id").order(SortOrder.DESC));*/
        // PageRequest 默认 从第0页开始
        searchQueryBuilder.withPageable(PageRequest.of(pageNum,pageSize, Sort.by(Sort.Direction.DESC,"id")));
        return R.ok(userRepository.search(searchQueryBuilder.build()));
    }

    /**
     * 查询
     * @param id
     * @return
     */
    @GetMapping("/find/{id}")
    public R<UserPojo> find (@PathVariable Long id){
        return R.ok(userRepository.findById(id).get());
    }

    /**
     * 查询
     * @param name
     * @return
     */
    @GetMapping("/find1/{name}")
    public R<List<UserPojo>> find1 (@PathVariable String name){
        MatchQueryBuilder queryBuilder = QueryBuilders.matchQuery("name", name);
        Iterable<UserPojo> search = userRepository.search(queryBuilder);
        List<UserPojo> list = new ArrayList<>();
        for (UserPojo userPojo : search) {
            list.add(userPojo);
        }
        return R.ok(list);
    }

    /**
     * 添加数据
     * @param name
     * @return
     */
    @GetMapping("/add/{name}")
    public R<String> add (@PathVariable String name){
        UserPojo userPojo = new UserPojo();
        userPojo.setId(ThreadLocalRandom.current().nextLong());
        userPojo.setAge(ThreadLocalRandom.current().nextInt());
        userPojo.setName(ThreadLocalRandom.current().nextInt() + "小二" + name);
        userPojo.setPassword("");
        userRepository.save(userPojo);
        return R.ok();
    }

    /**
     * 删除数据
     * @param id
     * @return
     */
    @GetMapping("/delete/{id}")
    public R<String> delete (@PathVariable Long id){
        userRepository.deleteById(id);
        return R.ok();
    }






    /********************************************** ElasticsearchRestTemplate使用 ********************************************/

    /**
     * 删除索引
     * @param name
     * @return
     */
    @GetMapping("/delete/index/{name}")
    public R<Boolean> deleteIndex (@PathVariable String name){
        return R.ok(elasticsearchRestTemplate.deleteIndex(name));
    }
}